// pages/myPosts/myPosts.js
const util = require("../../utils/util.js");
const api = require("../../config/api.js");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 页面状态
    loading: false,
    refreshing: false,

    // Tab相关
    activeTab: 0,
    tabs: [
      {
        name: "拼车",
        icon: "/static/icon/carpoolSelect.svg",
        iconInactive: "/static/icon/carpool.svg"
      },
      {
        name: "拼房",
        icon: "/static/icon/roomSelect.svg",
        iconInactive: "/static/icon/room.svg"
      },
      {
        name: "雪票",
        icon: "/static/icon/ticketSelect.svg",
        iconInactive: "/static/icon/ticket.svg"
      }
    ],

    // 筛选器相关
    currentFilters: [],
    carpoolFilters: [
      {
        text: "类型",
        arrow: "https://static.codia.ai/image/2025-10-25/Q5m6qvSwXV.png",
        active: false,
        options: [
          { text: "车找人", value: 0 },
          { text: "人找车", value: 1 }
        ],
        selectedValue: undefined
      },
      {
        text: "往返",
        arrow: "https://static.codia.ai/image/2025-10-25/coPUMd8CYp.png",
        active: false,
        options: [
          { text: "前往", value: 0 },
          { text: "返回", value: 1 }
        ],
        selectedValue: undefined
      },
      {
        text: "雪场",
        arrow: "https://static.codia.ai/image/2025-10-25/adY5nWjNXx.png",
        active: false,
        options: [
          { text: "万龙滑雪场", value: 1 },
          { text: "云顶滑雪场", value: 2 }
        ],
        selectedValue: undefined
      },
      {
        text: "日期",
        arrow: "https://static.codia.ai/image/2025-10-25/znXXzCJb87.png",
        active: false,
        options: [
          { text: "今天", value: "today" },
          { text: "明天", value: "tomorrow" },
          { text: "后天", value: "day_after_tomorrow" }
        ],
        selectedValue: undefined
      }
    ],
    roomFilters: [
      {
        text: "类型",
        arrow: "https://static.codia.ai/image/2025-10-25/Q5m6qvSwXV.png",
        active: false,
        options: [
          { text: "房找人", value: 0 },
          { text: "人找房", value: 1 }
        ],
        selectedValue: undefined
      },
      {
        text: "性别",
        arrow: "https://static.codia.ai/image/2025-10-25/coPUMd8CYp.png",
        active: false,
        options: [
          { text: "男", value: 0 },
          { text: "女", value: 1 }
        ],
        selectedValue: undefined
      },
      {
        text: "地点",
        arrow: "https://static.codia.ai/image/2025-10-25/adY5nWjNXx.png",
        active: false,
        options: [
          { text: "万龙滑雪场", value: 1 },
          { text: "云顶滑雪场", value: 2 }
        ],
        selectedValue: undefined
      },
      {
        text: "日期",
        arrow: "https://static.codia.ai/image/2025-10-25/znXXzCJb87.png",
        active: false,
        options: [
          { text: "今天", value: "today" },
          { text: "明天", value: "tomorrow" },
          { text: "后天", value: "day_after_tomorrow" }
        ],
        selectedValue: undefined
      }
    ],
    ticketFilters: [
      {
        text: "类型",
        arrow: "https://static.codia.ai/image/2025-10-08/xv6kLuGdSQ.png",
        active: false,
        options: [
          { text: "求购", value: 0 },
          { text: "转让", value: 1 }
        ],
        selectedValue: undefined
      },
      {
        text: "整/残",
        arrow: "https://static.codia.ai/image/2025-10-08/ssEap6ePBe.png",
        active: false,
        options: [
          { text: "整票", value: "0" },
          { text: "残票", value: "1" }
        ],
        selectedValue: undefined
      },
      {
        text: "雪场",
        arrow: "https://static.codia.ai/image/2025-10-08/uP1qSWkZm6.png",
        active: false,
        options: [
          { text: "万龙滑雪场", value: 1 },
          { text: "云顶滑雪场", value: 2 }
        ],
        selectedValue: undefined
      },
      {
        text: "日期",
        arrow: "https://static.codia.ai/image/2025-10-08/ssEap6ePBe.png",
        active: false,
        options: [
          { text: "今天", value: "today" },
          { text: "明天", value: "tomorrow" },
          { text: "后天", value: "day_after_tomorrow" }
        ],
        selectedValue: undefined
      }
    ],
    // ===== 雪场筛选弹窗状态 =====
    skiDropdownOpen: false, // 下拉面板开关
    skiDropdownTop: 0, // 下拉面板顶部定位
    selectedSkiId: null, // 用于回显的雪场ID
    skiFilterContext: null, // { tab: 0|1|2, filterIndex: number }
    // ===== SimpleDropdown组件相关 =====
    simpleDropdownOpen: false, // 简单下拉面板开关
    simpleDropdownTop: 0, // 简单下拉面板顶部定位
    simpleDropdownValue: null, // 当前选中的选项ID，用于回显
    simpleDropdownOptions: [], // 选项列表
    simpleDropdownContext: null, // { tab: 0|1|2, filterIndex: number }
    // ===== DatePicker组件相关 =====
    datePickerOpen: false, // 日期选择器开关
    datePickerTop: 0, // 日期选择器顶部定位
    selectedDate: null, // 选中的日期

    // 发布列表数据
    carpoolPostsList: [],
    roomPostsList: [],
    ticketPostsList: [],
    currentPostsList: [],

    // 分页相关 - 每个tab独立维护
    carpoolPage: 1,
    carpoolPageSize: 10,
    carpoolHasMore: true,
    carpoolTotal: 0,
    roomPage: 1,
    roomPageSize: 10,
    roomHasMore: true,
    roomTotal: 0,
    ticketPage: 1,
    ticketPageSize: 10,
    ticketHasMore: true,
    ticketTotal: 0,

    // 空状态
    isEmpty: false,

    // 用户信息
    userInfo: null,
    isLoggedIn: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("我的发布页面加载完成", options);
    this.checkLoginStatus();
    this.initCurrentTab();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log("我的发布页面渲染完成");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("我的发布页面显示");
    this.checkLoginStatus();

    // 如果已登录，加载数据
    if (this.data.isLoggedIn) {
      this.loadCurrentTabData(false);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log("我的发布页面隐藏");
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log("我的发布页面卸载");
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log("用户下拉刷新");
    this.refreshData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("页面触底，当前tab:", this.data.activeTab);

    const activeTab = this.data.activeTab;

    if (activeTab === 0) {
      // 拼车tab - 加载更多
      if (this.data.carpoolHasMore && !this.data.loading) {
        const nextPage = this.data.carpoolPage + 1;
        this.setData({
          carpoolPage: nextPage
        });
        this.loadCarpoolPosts(true);
      }
    } else if (activeTab === 1) {
      // 拼房tab - 加载更多
      if (this.data.roomHasMore && !this.data.loading) {
        const nextPage = this.data.roomPage + 1;
        this.setData({
          roomPage: nextPage
        });
        this.loadRoomPosts(true);
      }
    } else if (activeTab === 2) {
      // 雪票tab - 加载更多
      if (this.data.ticketHasMore && !this.data.loading) {
        const nextPage = this.data.ticketPage + 1;
        this.setData({
          ticketPage: nextPage
        });
        this.loadTicketPosts(true);
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "我的发布",
      path: "/pages/myPosts/myPosts"
    };
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus: function () {
    const userInfo = wx.getStorageSync("userInfo");
    const token = wx.getStorageSync("token");

    if (userInfo && token) {
      this.setData({
        userInfo: userInfo,
        isLoggedIn: true
      });
    } else {
      this.setData({
        userInfo: null,
        isLoggedIn: false
      });
    }
  },

  /**
   * 初始化当前Tab
   */
  initCurrentTab: function () {
    this.setData({
      currentFilters: this.data.carpoolFilters,
      currentPostsList: this.data.carpoolPostsList
    });
  },

  /**
   * Tab点击事件
   */
  onTabClick: function (e) {
    const index = e.currentTarget.dataset.index;
    console.log("Tab点击:", this.data.tabs[index].name);

    // 切换tab时关闭所有下拉框
    if (this.data.skiDropdownOpen) {
      this.closeSkiDropdown();
    }
    if (this.data.simpleDropdownOpen) {
      this.closeSimpleDropdown();
    }
    if (this.data.datePickerOpen) {
      this.closeDatePicker();
    }

    this.setData({
      activeTab: index
    });

    // 根据tab切换筛选器和数据
    this.switchTabData(index);
  },

  /**
   * 切换Tab数据
   */
  switchTabData: function (index) {
    let filters, postsList;

    switch (index) {
      case 0: // 拼车
        filters = this.data.carpoolFilters;
        postsList = this.data.carpoolPostsList;
        break;
      case 1: // 拼房
        filters = this.data.roomFilters;
        postsList = this.data.roomPostsList;
        break;
      case 2: // 雪票
        filters = this.data.ticketFilters;
        postsList = this.data.ticketPostsList;
        break;
      default:
        filters = this.data.carpoolFilters;
        postsList = this.data.carpoolPostsList;
    }

    this.setData({
      currentFilters: filters,
      currentPostsList: postsList,
      isEmpty: postsList.length === 0
    });

    // 如果当前tab没有数据，则加载数据
    if (postsList.length === 0 && this.data.isLoggedIn) {
      this.loadCurrentTabData(false);
    }
  },

  /**
   * 拼车筛选器点击事件
   */
  onCarpoolFilterClick: function (e) {
    const index = e.currentTarget.dataset.index;

    // 关闭其他下拉框
    if (this.data.skiDropdownOpen) {
      this.closeSkiDropdown();
    }
    if (this.data.simpleDropdownOpen) {
      this.closeSimpleDropdown();
    }
    if (this.data.datePickerOpen) {
      this.closeDatePicker();
    }

    if (index === 2) {
      // 雪场筛选 - 使用SkiDropdown组件
      this.openSkiFilterPopup({ tab: 0, filterIndex: index });
    } else if (index === 3) {
      // 日期筛选 - 使用DatePicker组件
      const that = this;
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;
          that.setData({ datePickerOpen: true, datePickerTop: top });
        });
    } else {
      // 类型、往返筛选 - 使用SimpleDropdown组件
      this.showCarpoolFilterOptions(index);
    }
  },

  /**
   * 拼房筛选器点击事件
   */
  onRoomFilterClick: function (e) {
    const index = e.currentTarget.dataset.index;

    // 关闭其他下拉框
    if (this.data.skiDropdownOpen) {
      this.closeSkiDropdown();
    }
    if (this.data.simpleDropdownOpen) {
      this.closeSimpleDropdown();
    }
    if (this.data.datePickerOpen) {
      this.closeDatePicker();
    }

    if (index === 2) {
      // 雪场筛选 - 使用SkiDropdown组件
      this.openSkiFilterPopup({ tab: 1, filterIndex: index });
    } else if (index === 3) {
      // 日期筛选 - 使用DatePicker组件
      const that = this;
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;
          that.setData({ datePickerOpen: true, datePickerTop: top });
        });
    } else {
      // 类型、性别筛选 - 使用SimpleDropdown组件
      this.showRoomFilterOptions(index);
    }
  },

  /**
   * 雪票筛选器点击事件
   */
  onTicketFilterClick: function (e) {
    const index = e.currentTarget.dataset.index;

    // 关闭其他下拉框
    if (this.data.skiDropdownOpen) {
      this.closeSkiDropdown();
    }
    if (this.data.simpleDropdownOpen) {
      this.closeSimpleDropdown();
    }
    if (this.data.datePickerOpen) {
      this.closeDatePicker();
    }

    if (index === 2) {
      // 雪场筛选 - 使用SkiDropdown组件
      this.openSkiFilterPopup({ tab: 2, filterIndex: index });
    } else if (index === 3) {
      // 日期筛选 - 使用DatePicker组件
      const that = this;
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;
          that.setData({ datePickerOpen: true, datePickerTop: top });
        });
    } else {
      // 类型、整/残筛选 - 使用SimpleDropdown组件
      this.showTicketFilterOptions(index);
    }
  },

  /**
   * 选择筛选选项
   */
  selectFilterOption: function (filterIndex, option) {
    const filters = this.data.currentFilters;
    filters[filterIndex].selectedValue = option.value;
    filters[filterIndex].active = option.value !== undefined;

    // 更新筛选器显示文本
    if (option.value !== undefined) {
      filters[filterIndex].text = option.text;
    } else {
      // 恢复原始文本
      const originalTexts = this.getOriginalFilterTexts();
      filters[filterIndex].text = originalTexts[filterIndex];
    }

    this.setData({
      currentFilters: filters
    });

    // 应用筛选条件
    this.applyFilters();
  },

  /**
   * 获取原始筛选器文本
   */
  getOriginalFilterTexts: function () {
    switch (this.data.activeTab) {
      case 0:
        return ["类型", "往返", "雪场", "日期"];
      case 1:
        return ["类型", "性别", "地点", "日期"];
      case 2:
        return ["类型", "整/残", "雪场", "日期"];
      default:
        return ["类型", "往返", "雪场", "日期"];
    }
  },

  /**
   * 应用筛选条件
   */
  applyFilters: function () {
    console.log("应用筛选条件");
    // 重置分页 - 根据当前tab重置对应的分页状态
    if (this.data.activeTab === 0) {
      this.setData({
        carpoolPage: 1,
        carpoolHasMore: true
      });
    } else if (this.data.activeTab === 1) {
      this.setData({
        roomPage: 1,
        roomHasMore: true
      });
    } else if (this.data.activeTab === 2) {
      this.setData({
        ticketPage: 1,
        ticketHasMore: true
      });
    }
    this.loadCurrentTabData(false);
  },

  /**
   * 刷新数据
   */
  refreshData: function () {
    this.setData({
      refreshing: true
    });

    // 根据当前tab重置对应的分页状态
    if (this.data.activeTab === 0) {
      this.setData({
        carpoolPage: 1,
        carpoolHasMore: true
      });
    } else if (this.data.activeTab === 1) {
      this.setData({
        roomPage: 1,
        roomHasMore: true
      });
    } else if (this.data.activeTab === 2) {
      this.setData({
        ticketPage: 1,
        ticketHasMore: true
      });
    }

    this.loadCurrentTabData(false);
  },

  /**
   * 加载当前Tab数据
   */
  loadCurrentTabData: function (isLoadMore) {
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: "请先登录",
        icon: "none"
      });
      return;
    }

    // 根据当前tab加载对应数据
    switch (this.data.activeTab) {
      case 0:
        this.loadCarpoolPosts(isLoadMore);
        break;
      case 1:
        this.loadRoomPosts(isLoadMore);
        break;
      case 2:
        this.loadTicketPosts(isLoadMore);
        break;
    }
  },

  /**
   * 通用API请求方法
   */
  requestApi: function (url, data = {}, method = "POST") {
    return new Promise((resolve, reject) => {
      const token = wx.getStorageSync("token");

      wx.request({
        url: url,
        method: method,
        data: data,
        header: {
          "Content-Type": "application/json",
          token: token
        },
        success: (res) => {
          if (res.statusCode === 200) {
            // 处理 401 错误
            if (res.data.errno == 401 || res.data.code == 401) {
              wx.navigateTo({
                url: "/pages/auth/btnAuth/btnAuth"
              });
              reject(new Error("用户未登录"));
              return;
            }
            resolve(res.data);
          } else {
            reject(new Error(`请求失败: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },

  /**
   * 构建拼车请求参数
   */
  buildCarpoolRequestParams: function () {
    // 参考home页面，直接从carpoolFilters中获取筛选条件
    const filters = this.data.carpoolFilters || [];
    const params = {};

    // 类型筛选 (0:车找人 1:人找车) - filterIndex: 0
    if (filters[0] && filters[0].selectedValue !== undefined) {
      params.type = filters[0].selectedValue;
    }

    // 往返筛选 (0:前往 1:返回) - filterIndex: 1
    if (filters[1] && filters[1].selectedValue !== undefined) {
      params.side = filters[1].selectedValue;
    }

    // 雪场筛选 (地址编号) - filterIndex: 2
    if (filters[2] && filters[2].selectedValue !== undefined) {
      params.address = filters[2].selectedValue;
    }

    // 日期筛选 (beginTime) - filterIndex: 3
    if (filters[3] && filters[3].selectedValue !== undefined) {
      params.beginTime = this.formatDateForAPI(filters[3].selectedValue);
    }

    return params;
  },

  /**
   * 格式化日期为API所需格式 (YYYY-MM-DD)
   */
  formatDateForAPI: function (dateValue) {
    if (!dateValue) return undefined;

    // 如果已经是YYYY-MM-DD格式，直接返回
    if (
      typeof dateValue === "string" &&
      /^\d{4}-\d{2}-\d{2}$/.test(dateValue)
    ) {
      return dateValue;
    }

    // 如果是日期对象，转换为YYYY-MM-DD格式
    if (dateValue instanceof Date) {
      return dateValue.toISOString().split("T")[0];
    }

    // 如果是时间戳，转换为YYYY-MM-DD格式
    if (typeof dateValue === "number") {
      const date = new Date(
        dateValue < 10000000000 ? dateValue * 1000 : dateValue
      );
      return date.toISOString().split("T")[0];
    }

    // 尝试解析字符串日期
    try {
      const date = new Date(dateValue);
      if (!isNaN(date.getTime())) {
        return date.toISOString().split("T")[0];
      }
    } catch (e) {
      console.warn("日期格式转换失败:", dateValue);
    }

    return undefined;
  },

  /**
   * 构建拼房请求参数
   */
  buildRoomRequestParams: function () {
    // 参考home页面，直接从roomFilters中获取筛选条件
    const filters = this.data.roomFilters || [];
    const params = {};

    // 类型筛选 (0:房找人 1:人找房) - filterIndex: 0
    if (filters[0] && filters[0].selectedValue !== undefined) {
      params.type = filters[0].selectedValue;
    }

    // 性别筛选 (0:男 1:女) - filterIndex: 1
    if (filters[1] && filters[1].selectedValue !== undefined) {
      params.sex = filters[1].selectedValue;
    }

    // 地点筛选 (地点ID) - filterIndex: 2
    if (filters[2] && filters[2].selectedValue !== undefined) {
      params.address = filters[2].selectedValue;
    }

    // 日期筛选 (beginTime) - filterIndex: 3
    if (filters[3] && filters[3].selectedValue !== undefined) {
      params.beginTime = this.formatDateForAPI(filters[3].selectedValue);
    }

    return params;
  },

  /**
   * 构建雪票请求参数
   */
  buildTicketRequestParams: function () {
    // 参考home页面，直接从ticketFilters中获取筛选条件
    const filters = this.data.ticketFilters || [];
    const params = {};

    // 类型筛选 (0:求购 1:转让) - filterIndex: 0
    if (filters[0] && filters[0].selectedValue !== undefined) {
      params.type = filters[0].selectedValue;
    }

    // 整/残筛选 (0:整票 1:残票) - filterIndex: 1
    if (filters[1] && filters[1].selectedValue !== undefined) {
      params.isFull = filters[1].selectedValue;
    }

    // 雪场筛选 (雪场ID) - filterIndex: 2
    if (filters[2] && filters[2].selectedValue !== undefined) {
      params.address = filters[2].selectedValue;
    }

    // 日期筛选 (beginTime) - filterIndex: 3
    if (filters[3] && filters[3].selectedValue !== undefined) {
      params.beginTime = this.formatDateForAPI(filters[3].selectedValue);
    }

    return params;
  },

  /**
   * 加载拼车发布数据
   */
  loadCarpoolPosts: function (isLoadMore) {
    const that = this;

    // 如果不是加载更多，重置为第一页
    if (!isLoadMore) {
      that.setData({
        carpoolPage: 1,
        carpoolHasMore: true,
        carpoolPostsList: []
      });
    }

    that.setData({
      loading: true
    });

    // 构建请求参数，包含分页参数
    const requestParams = {
      ...that.buildCarpoolRequestParams(),
      page: that.data.carpoolPage,
      pageSize: that.data.carpoolPageSize
    };

    console.log("拼车请求参数:", requestParams);
    console.log("拼车API地址:", api.CarList);

    that
      .requestApi(api.CarList, requestParams)
      .then((response) => {
        console.log("拼车数据API响应:", response);

        if (response.code === "200" || response.code === 200) {
          // 从新的响应格式中获取数据：res.data.records
          const records =
            response.data && response.data.records ? response.data.records : [];
          const total =
            response.data && response.data.total ? response.data.total : 0;

          // 转换API数据为UI数据格式
          const newCards = that.transformCarpoolData(records || []);

          // 如果是加载更多，追加数据；否则替换数据
          const carpoolPostsList = isLoadMore
            ? [...that.data.carpoolPostsList, ...newCards]
            : newCards;

          // 判断是否还有更多数据
          const hasMore = carpoolPostsList.length < total;

          that.setData({
            carpoolPostsList: carpoolPostsList,
            currentPostsList: carpoolPostsList,
            carpoolTotal: total,
            carpoolHasMore: hasMore,
            loading: false,
            refreshing: false,
            isEmpty: carpoolPostsList.length === 0
          });
        } else {
          throw new Error(response.msg || "获取数据失败");
        }
      })
      .catch((error) => {
        console.error("拼车数据加载失败:", error);

        // 显示错误信息
        wx.showToast({
          title: error.message || "加载失败",
          icon: "none"
        });

        that.setData({
          loading: false,
          refreshing: false,
          isEmpty: true
        });
      })
      .finally(() => {
        wx.stopPullDownRefresh();
      });
  },

  /**
   * 加载拼房发布数据
   */
  loadRoomPosts: function (isLoadMore) {
    const that = this;

    // 如果不是加载更多，重置为第一页
    if (!isLoadMore) {
      that.setData({
        roomPage: 1,
        roomHasMore: true,
        roomPostsList: []
      });
    }

    that.setData({
      loading: true
    });

    // 构建请求参数，包含分页参数
    const requestParams = {
      ...that.buildRoomRequestParams(),
      page: that.data.roomPage,
      pageSize: that.data.roomPageSize
    };

    console.log("拼房请求参数:", requestParams);
    console.log("拼房API地址:", api.HomeList);

    that
      .requestApi(api.HomeList, requestParams)
      .then((response) => {
        console.log("拼房数据API响应:", response);

        if (response.code === "200" || response.code === 200) {
          // 从新的响应格式中获取数据：res.data.records
          const records =
            response.data && response.data.records ? response.data.records : [];
          const total =
            response.data && response.data.total ? response.data.total : 0;

          // 转换API数据为UI数据格式
          const newCards = that.transformRoomData(records || []);

          // 如果是加载更多，追加数据；否则替换数据
          const roomPostsList = isLoadMore
            ? [...that.data.roomPostsList, ...newCards]
            : newCards;

          // 判断是否还有更多数据
          const hasMore = roomPostsList.length < total;

          that.setData({
            roomPostsList: roomPostsList,
            currentPostsList: roomPostsList,
            roomTotal: total,
            roomHasMore: hasMore,
            loading: false,
            refreshing: false,
            isEmpty: roomPostsList.length === 0
          });
        } else {
          throw new Error(response.msg || "获取数据失败");
        }
      })
      .catch((error) => {
        console.error("拼房数据加载失败:", error);

        // 显示错误信息
        wx.showToast({
          title: error.message || "加载失败",
          icon: "none"
        });

        that.setData({
          loading: false,
          refreshing: false,
          isEmpty: true
        });
      })
      .finally(() => {
        wx.stopPullDownRefresh();
      });
  },

  /**
   * 加载雪票发布数据
   */
  loadTicketPosts: function (isLoadMore) {
    const that = this;

    // 如果不是加载更多，重置为第一页
    if (!isLoadMore) {
      that.setData({
        ticketPage: 1,
        ticketHasMore: true,
        ticketPostsList: []
      });
    }

    that.setData({
      loading: true
    });

    // 构建请求参数，包含分页参数
    const requestParams = {
      ...that.buildTicketRequestParams(),
      page: that.data.ticketPage,
      pageSize: that.data.ticketPageSize
    };

    console.log("雪票请求参数:", requestParams);
    console.log("雪票API地址:", api.TicketList);

    that
      .requestApi(api.TicketList, requestParams)
      .then((response) => {
        console.log("雪票数据API响应:", response);

        if (response.code === "200" || response.code === 200) {
          // 从新的响应格式中获取数据：res.data.records
          const records =
            response.data && response.data.records ? response.data.records : [];
          const total =
            response.data && response.data.total ? response.data.total : 0;

          // 转换API数据为UI数据格式
          const newCards = that.transformTicketData(records || []);

          // 如果是加载更多，追加数据；否则替换数据
          const ticketPostsList = isLoadMore
            ? [...that.data.ticketPostsList, ...newCards]
            : newCards;

          // 判断是否还有更多数据
          const hasMore = ticketPostsList.length < total;

          that.setData({
            ticketPostsList: ticketPostsList,
            currentPostsList: ticketPostsList,
            ticketTotal: total,
            ticketHasMore: hasMore,
            loading: false,
            refreshing: false,
            isEmpty: ticketPostsList.length === 0
          });
        } else {
          throw new Error(response.msg || "获取数据失败");
        }
      })
      .catch((error) => {
        console.error("雪票数据加载失败:", error);

        // 显示错误信息
        wx.showToast({
          title: error.message || "加载失败",
          icon: "none"
        });

        that.setData({
          loading: false,
          refreshing: false,
          isEmpty: true
        });
      })
      .finally(() => {
        wx.stopPullDownRefresh();
      });
  },

  /**
   * 格式化日期和时间（使用goTime字段）- 参考home页面
   */
  formatDateWithTime: function (date, goTime) {
    if (!date) return "";

    try {
      // 判断是秒级时间戳还是毫秒级时间戳，或者是日期字符串
      let dateObj;
      if (typeof date === "string") {
        // 如果是日期字符串，如 "2024-01-01"
        dateObj = new Date(date);
      } else {
        dateObj = date < 10000000000 ? new Date(date * 1000) : new Date(date);
      }

      // 验证日期是否有效
      if (isNaN(dateObj.getTime())) {
        return "";
      }

      const now = new Date();
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
      const dayAfterTomorrow = new Date(
        today.getTime() + 2 * 24 * 60 * 60 * 1000
      );

      const targetDate = new Date(
        dateObj.getFullYear(),
        dateObj.getMonth(),
        dateObj.getDate()
      );

      let prefix = "";
      if (targetDate.getTime() === today.getTime()) {
        prefix = "今天";
      } else if (targetDate.getTime() === tomorrow.getTime()) {
        prefix = "明天";
      } else if (targetDate.getTime() === dayAfterTomorrow.getTime()) {
        prefix = "后天";
      } else {
        const month = dateObj.getMonth() + 1;
        const day = dateObj.getDate();
        const dayNames = [
          "周日",
          "周一",
          "周二",
          "周三",
          "周四",
          "周五",
          "周六"
        ];
        const dayName = dayNames[dateObj.getDay()];
        // 如果有goTime，使用goTime；否则不显示时间
        if (goTime) {
          return `${month}.${day} ${dayName} ${goTime}`;
        }
        return `${month}.${day} ${dayName}`;
      }

      // 如果有goTime，使用goTime；否则使用从日期对象中提取的时间
      const timeStr =
        goTime ||
        `${dateObj.getHours().toString().padStart(2, "0")}:${dateObj
          .getMinutes()
          .toString()
          .padStart(2, "0")}`;
      return `${prefix} ${timeStr}`;
    } catch (error) {
      console.error("时间格式化失败:", error);
      return "";
    }
  },

  /**
   * 转换API数据为UI数据格式 - 参考home页面
   */
  transformCarpoolData: function (carList) {
    const that = this;
    return carList.map(function (item) {
      return {
        id: item.id, // 保留原始ID，用于跳转详情页
        type: "carpool", // 保留type字段用于myPosts页面
        tripType: item.side === 0 ? "outbound" : "return",
        tripTypeText: item.side === 0 ? "前往" : "返回",
        serviceType:
          item.type === 0
            ? "/static/images/chezhaoren.svg"
            : "/static/images/renzhaoche.svg",
        tripTime: that.formatDateWithTime(item.date, item.goTime),
        startLocation: item.fromAddr,
        endLocation: item.toAddr,
        userAvatar:
          item.imageUrl ||
          "https://static.codia.ai/image/2025-10-08/z0ouKB6QcC.png",
        userName: item.nickName,
        // status: item.type === 0 ? "可拼" : "求拼",
        peopleCount: item.people + "人",
        boardCount: item.ski > 0 ? item.ski + "板" : "",
        bagCount: item.bag > 0 ? item.bag + "板包" : "",
        price: item.price.toString(),
        peopleIcon: "https://static.codia.ai/image/2025-10-08/L2juZcsFLH.png",
        boardIcon: "https://static.codia.ai/image/2025-10-08/8xYeG5naGc.png",
        bagIcon: "https://static.codia.ai/image/2025-10-08/T41amkDiie.png",
        isClub: item.isClub, // 添加isClub字段
        // myPosts页面特有的字段
        statusCode: item.status,
        isExpired: item.status === 0,
        statusText:
          item.status === 0 ? "已过期" : item.type === 0 ? "可拼" : "求拼"
      };
    });
  },

  /**
   * 格式化日期显示
   */
  formatDate: function (dateString) {
    if (!dateString) return "";

    const date = new Date(dateString);
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
    const dayAfterTomorrow = new Date(
      today.getTime() + 2 * 24 * 60 * 60 * 1000
    );

    const targetDate = new Date(
      date.getFullYear(),
      date.getMonth(),
      date.getDate()
    );

    if (targetDate.getTime() === today.getTime()) {
      return `今天 ${date.getHours().toString().padStart(2, "0")}:${date
        .getMinutes()
        .toString()
        .padStart(2, "0")}`;
    } else if (targetDate.getTime() === tomorrow.getTime()) {
      return `明天 ${date.getHours().toString().padStart(2, "0")}:${date
        .getMinutes()
        .toString()
        .padStart(2, "0")}`;
    } else if (targetDate.getTime() === dayAfterTomorrow.getTime()) {
      return `后天 ${date.getHours().toString().padStart(2, "0")}:${date
        .getMinutes()
        .toString()
        .padStart(2, "0")}`;
    } else {
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const hours = date.getHours().toString().padStart(2, "0");
      const minutes = date.getMinutes().toString().padStart(2, "0");
      return `${month}.${day} ${hours}:${minutes}`;
    }
  },

  /**
   * 转换拼房API数据为UI显示格式
   */
  transformRoomData: function (apiData) {
    const that = this;
    return apiData.map((item) => {
      return {
        id: item.id,
        type: item.type === 0 ? "room-seeking" : "person-seeking",
        typeText: item.type === 0 ? "房找人" : "人找房",
        dateRange: that.formatDateRange(item.beginTime, item.endTime),
        duration: that.calculateDuration(item.beginTime, item.endTime),
        hotelIcon:
          item.type === 0
            ? "https://static.codia.ai/image/2025-10-19/mb9v9tEaFF.png"
            : "https://static.codia.ai/image/2025-10-19/sJWUhHWs5J.png",
        hotelName: item.address || "酒店信息待完善",
        skiResortIcon:
          item.type === 0
            ? "https://static.codia.ai/image/2025-10-19/9Y9p75bNgy.png"
            : "https://static.codia.ai/image/2025-10-19/FyonST16C3.png",
        skiResortName: item.skiAddress || "", // 直接使用skiAddress字段
        userAvatar:
          item.imageUrl ||
          "https://static.codia.ai/image/2025-10-19/TW0gtYHhM5.png",
        userName: item.nickName || "昵称文字",
        skiLodgeIcon:
          item.type === 0
            ? "https://static.codia.ai/image/2025-10-19/Xuz9Y3TgZS.png"
            : "https://static.codia.ai/image/2025-10-19/PwnjX2PR6s.png",
        skiLodge: item.ski === 0 ? "单房" : "住滑",
        bedTypeIcon:
          item.type === 0
            ? "https://static.codia.ai/image/2025-10-19/ZKrzQQ9N6N.png"
            : "https://static.codia.ai/image/2025-10-19/ojB4h4j7De.png",
        bedType: that.getBedTypeText(item.homeType),
        genderIcon:
          item.limitSex === 0
            ? "https://static.codia.ai/image/2025-10-19/RTn4SkXmeP.png"
            : "https://static.codia.ai/image/2025-10-19/bHpck7WcLw.png",
        genderRequirement:
          item.limitSex === 0 ? "男" : item.limitSex === 1 ? "女" : "不限",
        price: item.price.toString(),
        isClub: item.isClub,
        statusCode: item.status,
        detail: item.detail,
        isExpired: item.status === 0,
        statusText:
          item.status === 0 ? "已过期" : item.type === 0 ? "房找人" : "人找房"
      };
    });
  },

  /**
   * 格式化日期范围
   */
  formatDateRange: function (beginTime, endTime) {
    if (!beginTime || !endTime) {
      return "";
    }

    // 格式化开始时间
    const beginStr = this.formatDateForDisplay(beginTime);
    // 格式化结束时间
    const endStr = this.formatDateForDisplay(endTime);

    return `${beginStr}-${endStr}`;
  },

  /**
   * 格式化时间为显示格式
   */
  formatDateForDisplay: function (timestamp) {
    if (!timestamp) return "";

    try {
      // 判断是秒级时间戳还是毫秒级时间戳
      const date =
        timestamp < 10000000000
          ? new Date(timestamp * 1000)
          : new Date(timestamp);

      // 验证日期是否有效
      if (isNaN(date.getTime())) {
        return "";
      }

      const month = date.getMonth() + 1;
      const day = date.getDate();
      const dayNames = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      const dayName = dayNames[date.getDay()];

      return `${month}.${day}${dayName}`;
    } catch (error) {
      console.error("日期格式化失败:", error);
      return "";
    }
  },

  /**
   * 计算住宿天数
   */
  calculateDuration: function (beginTime, endTime) {
    if (!beginTime || !endTime) {
      return "";
    }

    try {
      let begin, end;

      // 处理开始时间
      if (typeof beginTime === "string" && beginTime.includes("-")) {
        // 日期字符串格式，如 "2024-12-22"
        begin = new Date(beginTime);
      } else {
        // 时间戳格式（可能是秒级或毫秒级）
        const beginTimestamp =
          typeof beginTime === "string" ? parseFloat(beginTime) : beginTime;
        begin =
          beginTimestamp < 10000000000
            ? new Date(beginTimestamp * 1000)
            : new Date(beginTimestamp);
      }

      // 处理结束时间
      if (typeof endTime === "string" && endTime.includes("-")) {
        // 日期字符串格式，如 "2024-12-22"
        end = new Date(endTime);
      } else {
        // 时间戳格式（可能是秒级或毫秒级）
        const endTimestamp =
          typeof endTime === "string" ? parseFloat(endTime) : endTime;
        end =
          endTimestamp < 10000000000
            ? new Date(endTimestamp * 1000)
            : new Date(endTimestamp);
      }

      // 验证日期是否有效
      if (isNaN(begin.getTime()) || isNaN(end.getTime())) {
        console.warn("无效的日期:", beginTime, endTime);
        return "";
      }

      // 计算日期差（按天计算，不考虑具体时间）
      const beginDate = new Date(
        begin.getFullYear(),
        begin.getMonth(),
        begin.getDate()
      );
      const endDate = new Date(
        end.getFullYear(),
        end.getMonth(),
        end.getDate()
      );
      const diffTime = endDate.getTime() - beginDate.getTime();
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

      if (diffDays <= 0) {
        return "";
      }

      return `| ${diffDays}晚`;
    } catch (error) {
      console.error("计算住宿天数失败:", error);
      return "";
    }
  },

  /**
   * 获取星期文本
   */
  getWeekdayText: function (day) {
    const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    return weekdays[day];
  },

  /**
   * 提取酒店名称
   */
  extractHotelName: function (address) {
    if (!address) return "崇礼酒店";
    // 简单提取，实际可能需要更复杂的逻辑
    return address.includes("酒店") ? address : "崇礼酒店";
  },

  /**
   * 提取滑雪场名称
   */
  extractSkiResortName: function (address) {
    if (!address) return "云顶滑雪场";
    // 简单提取，实际可能需要更复杂的逻辑
    if (address.includes("万龙")) return "万龙滑雪场";
    if (address.includes("云顶")) return "云顶滑雪场";
    return "云顶滑雪场";
  },

  /**
   * 获取床型文本
   */
  getBedTypeText: function (homeType) {
    const bedTypeMap = {
      0: "双床",
      1: "大床",
      2: "单床"
    };
    return bedTypeMap[homeType] || "双床";
  },

  /**
   * 根据雪场ID获取雪场名称
   */
  getSkiResortName: function (skiResortId) {
    if (!this.data.publicInfo || !this.data.publicInfo.skiList) {
      return "万龙滑雪场"; // 默认值
    }

    const skiResort = this.data.publicInfo.skiList.find(
      (ski) => ski.id === skiResortId
    );
    return skiResort ? skiResort.name : "万龙滑雪场";
  },

  /**
   * 获取性别要求文本
   */
  getGenderRequirementText: function (limitSex) {
    const genderTexts = ["要求男", "要求女", "不限"];
    return genderTexts[limitSex] || "不限";
  },

  /**
   * 转换雪票API数据为UI显示格式
   */
  transformTicketData: function (apiData) {
    return apiData.map((item) => {
      return {
        id: item.id,
        type: item.type === 0 ? "求购" : "转让",
        ticketType: this.getTicketTypeText(item.ticketType),
        detail: item.detail,
        dateTime: this.formatTicketDateTime(item.date),
        location: item.skiAddress || item.address || "",
        meetingInfo: item.getType === 0 ? "面交" : "线上",
        isFull: item.isFull,
        userAvatar:
          item.imageUrl ||
          "https://static.codia.ai/image/2025-10-19/S0NzN69kEs.png",
        userName: item.nickName || "昵称文字",
        quantity: `${item.count}张`,
        duration: this.getTicketDurationText(item.ticketType),
        delivery: item.getType === 0 ? "面交" : "线上",
        price: item.price.toString(),
        locationIcon: "https://static.codia.ai/image/2025-10-19/x7vFQxgM9d.png",
        meetingIcon: "https://static.codia.ai/image/2025-10-19/DsfqyDAgqc.png",
        quantityIcon: "https://static.codia.ai/image/2025-10-19/Ehi0T29ULU.png",
        durationIcon: "https://static.codia.ai/image/2025-10-19/AR4zf0WytE.png",
        deliveryIcon: "https://static.codia.ai/image/2025-10-19/6eThc7noKN.png",
        isClub: item.isClub,
        statusCode: item.status,
        isExpired: item.status === 0,
        statusText:
          item.status === 0 ? "已过期" : item.type === 0 ? "求购" : "转让"
      };
    });
  },

  /**
   * 获取雪票类型文本
   */
  getTicketTypeText: function (ticketType) {
    const ticketTypes = ["1日", "1.5日", "2日", "多日"];
    return ticketTypes[ticketType] || "1日";
  },

  /**
   * 格式化雪票日期时间
   */
  formatTicketDateTime: function (dateString) {
    if (!dateString) return "";

    const date = new Date(dateString);
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const weekday = this.getWeekdayText(date.getDay());

    return `${month}.${day}${weekday} 上午`;
  },

  /**
   * 获取雪票时长文本
   */
  getTicketDurationText: function (ticketType) {
    const durations = ["1日", "1.5日", "2日", "多日"];
    return durations[ticketType] || "1日";
  },

  /**
   * 获取拼房模拟数据
   */
  getMockRoomData: function () {
    return [
      {
        id: 1,
        type: "room-seeking",
        typeText: "房找人",
        dateRange: "12.22周三-12.30周四",
        duration: "| 4晚",
        hotelIcon: "https://static.codia.ai/image/2025-10-19/mb9v9tEaFF.png",
        hotelName: "崇礼酒店",
        skiResortIcon:
          "https://static.codia.ai/image/2025-10-19/9Y9p75bNgy.png",
        skiResortName: "云顶滑雪场",
        userAvatar: "https://static.codia.ai/image/2025-10-19/TW0gtYHhM5.png",
        userName: "昵称文字",
        skiLodgeIcon: "https://static.codia.ai/image/2025-10-19/Xuz9Y3TgZS.png",
        skiLodge: "住滑",
        bedTypeIcon: "https://static.codia.ai/image/2025-10-19/ZKrzQQ9N6N.png",
        bedType: "双床",
        genderIcon: "https://static.codia.ai/image/2025-10-19/RTn4SkXmeP.png",
        genderRequirement: "要求男",
        price: "200"
      }
    ];
  },

  /**
   * 获取雪票模拟数据
   */
  getMockTicketData: function () {
    return [
      {
        id: 1,
        type: "求购",
        ticketType: "残票",
        dateTime: "12.22周六 上午",
        location: "云顶滑雪场",
        meetingInfo: "面交",
        userAvatar: "https://static.codia.ai/image/2025-10-19/S0NzN69kEs.png",
        userName: "昵称文字",
        quantity: "1张",
        duration: "1.5日",
        delivery: "面交",
        price: "150",
        locationIcon: "https://static.codia.ai/image/2025-10-19/x7vFQxgM9d.png",
        meetingIcon: "https://static.codia.ai/image/2025-10-19/DsfqyDAgqc.png",
        quantityIcon: "https://static.codia.ai/image/2025-10-19/Ehi0T29ULU.png",
        durationIcon: "https://static.codia.ai/image/2025-10-19/AR4zf0WytE.png",
        deliveryIcon: "https://static.codia.ai/image/2025-10-19/6eThc7noKN.png"
      }
    ];
  },

  /**
   * 点击发布项
   */
  onPostItemClick: function (e) {
    const postId = e.currentTarget.dataset.id;
    const postType = e.currentTarget.dataset.type;

    console.log("点击发布项:", postId, postType);

    // 根据类型跳转到对应的详情页面
    let detailUrl = "";
    switch (postType) {
      case "carpool":
        detailUrl = `/pages/carpoolDetail/carpoolDetail?id=${postId}`;
        break;
      case "room-seeking":
      case "person-seeking":
        // 拼房类型：room-seeking (房找人) 或 person-seeking (人找房)
        detailUrl = `/pages/roomSharingDetail/roomSharingDetail?id=${postId}`;
        break;
      case "求购":
      case "转让":
        // 雪票类型：求购 或 转让
        detailUrl = `/pages/ticketDetail/ticketDetail?id=${postId}`;
        break;
      default:
        wx.showToast({
          title: "未知类型",
          icon: "none"
        });
        return;
    }

    wx.navigateTo({
      url: detailUrl,
      success: function () {
        console.log("跳转到详情页面成功");
      },
      fail: function (err) {
        console.error("跳转到详情页面失败:", err);
        wx.showToast({
          title: "页面跳转失败",
          icon: "none"
        });
      }
    });
  },

  /**
   * 编辑发布
   */
  onEditPost: function (e) {
    const postId = e.currentTarget.dataset.id;
    const postType = e.currentTarget.dataset.type;

    console.log("编辑发布:", postId, postType);

    // 根据类型跳转到对应的编辑页面
    let editUrl = "";
    switch (postType) {
      case "carpool":
        editUrl = `/pages/carpoolAdd/carpoolAdd?id=${postId}`;
        break;
      case "room-seeking":
      case "person-seeking":
        editUrl = `/pages/roomSharingAdd/roomSharingAdd?id=${postId}`;
        break;
      case "求购":
      case "转让":
        // ticket-status：求购 或 转让
        editUrl = `/pages/ticketAdd/ticketAdd?id=${postId}`;
        break;
      default:
        wx.showToast({
          title: "未知类型",
          icon: "none"
        });
        return;
    }

    wx.navigateTo({
      url: editUrl,
      success: function () {
        console.log("跳转到编辑页面成功");
      },
      fail: function (err) {
        console.error("跳转到编辑页面失败:", err);
        wx.showToast({
          title: "页面跳转失败",
          icon: "none"
        });
      }
    });
  },

  /**
   * 再发一单
   */
  onRepost: function (e) {
    const postId = e.currentTarget.dataset.id;
    const postType = e.currentTarget.dataset.type;

    console.log("再发一单:", postId, postType);

    // 根据类型跳转到对应的新增页面，传递copyId参数用于回填数据
    let addUrl = "";
    switch (postType) {
      case "carpool":
        addUrl = `/pages/carpoolAdd/carpoolAdd?copyId=${postId}`;
        break;
      case "room-seeking":
      case "person-seeking":
        addUrl = `/pages/roomSharingAdd/roomSharingAdd?copyId=${postId}`;
        break;
      case "求购":
      case "转让":
        // 雪票类型：求购 或 转让
        addUrl = `/pages/ticketAdd/ticketAdd?copyId=${postId}`;
        break;
      default:
        wx.showToast({
          title: "未知类型",
          icon: "none"
        });
        return;
    }

    wx.navigateTo({
      url: addUrl,
      success: function () {
        console.log("跳转到新增页面成功");
      },
      fail: function (err) {
        console.error("跳转到新增页面失败:", err);
        wx.showToast({
          title: "页面跳转失败",
          icon: "none"
        });
      }
    });
  },

  /**
   * 停止发布
   */
  onStopPost: function (e) {
    const postId = e.currentTarget.dataset.id;
    const postType = e.currentTarget.dataset.type;

    console.log("停止发布:", postId, postType);

    wx.showModal({
      title: "确认停止",
      content: "确定要停止发布这条信息吗？",
      success: (res) => {
        if (res.confirm) {
          this.stopPost(postId, postType);
        }
      }
    });
  },

  /**
   * 执行停止发布操作
   */
  stopPost: function (postId, postType) {
    const that = this;

    wx.showLoading({
      title: "处理中...",
      mask: true
    });

    console.log("执行停止发布操作:", postId, postType);

    const api = require("../../config/api.js");

    // 根据不同的类型调用不同的停止发布接口
    // 只传 id 和 status=0
    let apiUrl;

    switch (postType) {
      case "carpool":
        // 拼车类型，调用编辑拼车接口
        apiUrl = api.CarEdit;
        break;
      case "room-seeking":
      case "person-seeking":
      case "room":
        // 拼房类型
        apiUrl = api.HomeEdit;
        break;
      case "求购":
      case "转让":
      case "ticket":
        // 雪票类型
        apiUrl = api.TicketEdit;
        break;
      default:
        wx.hideLoading();
        wx.showToast({
          title: "未知类型",
          icon: "none"
        });
        return;
    }

    console.log("停止发布接口:", apiUrl);

    // 调用真实的停止发布API
    const stopData = {
      id: postId,
      status: 0
    };

    console.log("停止发布请求参数:", stopData);

    this.requestApi(apiUrl, stopData)
      .then((response) => {
        console.log("停止发布响应:", response);

        if (
          response.code === 200 ||
          response.code === "200" ||
          response.code === 0
        ) {
          wx.hideLoading();

          wx.showToast({
            title: "已停止发布",
            icon: "success"
          });

          // 延迟一点时间后刷新页面，让用户看到成功提示
          setTimeout(() => {
            // 重新加载数据，刷新当前Tab的数据
            if (that.data.activeTab === 0) {
              that.setData({
                carpoolPage: 1,
                carpoolHasMore: true
              });
            } else if (that.data.activeTab === 1) {
              that.setData({
                roomPage: 1,
                roomHasMore: true
              });
            } else if (that.data.activeTab === 2) {
              that.setData({
                ticketPage: 1,
                ticketHasMore: true
              });
            }
            that.loadCurrentTabData(false);
          }, 500);
        } else {
          wx.hideLoading();
          wx.showToast({
            title: response.msg || "停止发布失败",
            icon: "none"
          });
        }
      })
      .catch((error) => {
        console.error("停止发布失败:", error);

        wx.hideLoading();

        wx.showToast({
          title: error.message || "网络错误，请重试",
          icon: "none"
        });
      });
  },

  /**
   * 登录按钮点击
   */
  onLoginClick: function () {
    util.executeWithLoginCheck(
      () => {
        // 用户已登录，更新页面状态
        this.checkLoginStatus();
        this.loadMyPosts();
        wx.showToast({
          title: "登录成功",
          icon: "success"
        });
      },
      "查看我的发布需要先登录，是否立即登录？",
      "/pages/myPosts/myPosts"
    );
  },

  /**
   * 显示拼车筛选选项 - 使用SimpleDropdown组件
   */
  showCarpoolFilterOptions: function (filterIndex) {
    const filter = this.data.carpoolFilters[filterIndex];

    if (
      this.data.simpleDropdownOpen &&
      this.data.simpleDropdownContext &&
      this.data.simpleDropdownContext.tab === 0 &&
      this.data.simpleDropdownContext.filterIndex === filterIndex
    ) {
      this.closeSimpleDropdown();
      return;
    }

    const options = filter.options.map((option, index) => ({
      id: option.value !== undefined ? option.value : index,
      name: option.text
    }));

    const selectedValue =
      filter.selectedValue !== undefined ? filter.selectedValue : null;
    const that = this;

    if (this.data.simpleDropdownOpen) {
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;

          that.setData({
            simpleDropdownTop: top,
            simpleDropdownValue: selectedValue,
            simpleDropdownOptions: options,
            simpleDropdownContext: { tab: 0, filterIndex: filterIndex }
          });
        });
    } else {
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;

          that.setData({
            simpleDropdownOpen: true,
            simpleDropdownTop: top,
            simpleDropdownValue: selectedValue,
            simpleDropdownOptions: options,
            simpleDropdownContext: { tab: 0, filterIndex: filterIndex }
          });
        });
    }
  },

  /**
   * 显示拼房筛选选项 - 使用SimpleDropdown组件
   */
  showRoomFilterOptions: function (filterIndex) {
    const filter = this.data.roomFilters[filterIndex];

    if (
      this.data.simpleDropdownOpen &&
      this.data.simpleDropdownContext &&
      this.data.simpleDropdownContext.tab === 1 &&
      this.data.simpleDropdownContext.filterIndex === filterIndex
    ) {
      this.closeSimpleDropdown();
      return;
    }

    const options = filter.options.map((option, index) => ({
      id: option.value !== undefined ? option.value : index,
      name: option.text
    }));

    const selectedValue =
      filter.selectedValue !== undefined ? filter.selectedValue : null;
    const that = this;

    if (this.data.simpleDropdownOpen) {
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;

          that.setData({
            simpleDropdownTop: top,
            simpleDropdownValue: selectedValue,
            simpleDropdownOptions: options,
            simpleDropdownContext: { tab: 1, filterIndex: filterIndex }
          });
        });
    } else {
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;

          that.setData({
            simpleDropdownOpen: true,
            simpleDropdownTop: top,
            simpleDropdownValue: selectedValue,
            simpleDropdownOptions: options,
            simpleDropdownContext: { tab: 1, filterIndex: filterIndex }
          });
        });
    }
  },

  /**
   * 显示雪票筛选选项 - 使用SimpleDropdown组件
   */
  showTicketFilterOptions: function (filterIndex) {
    const filter = this.data.ticketFilters[filterIndex];

    if (
      this.data.simpleDropdownOpen &&
      this.data.simpleDropdownContext &&
      this.data.simpleDropdownContext.tab === 2 &&
      this.data.simpleDropdownContext.filterIndex === filterIndex
    ) {
      this.closeSimpleDropdown();
      return;
    }

    const options = filter.options.map((option, index) => ({
      id: option.value !== undefined ? option.value : index,
      name: option.text
    }));

    const selectedValue =
      filter.selectedValue !== undefined ? filter.selectedValue : null;
    const that = this;

    if (this.data.simpleDropdownOpen) {
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;

          that.setData({
            simpleDropdownTop: top,
            simpleDropdownValue: selectedValue,
            simpleDropdownOptions: options,
            simpleDropdownContext: { tab: 2, filterIndex: filterIndex }
          });
        });
    } else {
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;

          that.setData({
            simpleDropdownOpen: true,
            simpleDropdownTop: top,
            simpleDropdownValue: selectedValue,
            simpleDropdownOptions: options,
            simpleDropdownContext: { tab: 2, filterIndex: filterIndex }
          });
        });
    }
  },

  /**
   * SimpleDropdown组件change事件处理
   */
  onSimpleDropdownChange: function (e) {
    const optionId = e.detail.value;
    const optionName = e.detail.name;
    const ctx = this.data.simpleDropdownContext;

    if (!ctx) {
      this.closeSimpleDropdown();
      return;
    }

    const isReset =
      optionId === null || optionId === undefined || optionId === "";

    if (ctx.tab === 0) {
      const filters = this.data.carpoolFilters;
      const filter = filters[ctx.filterIndex];

      if (isReset) {
        filters[ctx.filterIndex].selectedValue = undefined;
        filters[ctx.filterIndex].active = false;
        const originalTexts = ["类型", "往返", "雪场", "日期"];
        filters[ctx.filterIndex].text = originalTexts[ctx.filterIndex];

        this.setData({
          carpoolFilters: filters
        });

        this.applyFilters();
        this.closeSimpleDropdown();
      } else {
        const option = filter.options.find((opt) => {
          return (
            opt.value === optionId || String(opt.value) === String(optionId)
          );
        });

        if (option) {
          filters[ctx.filterIndex].selectedValue = option.value;
          filters[ctx.filterIndex].active = true;
          filters[ctx.filterIndex].text = option.text;

          this.setData({
            carpoolFilters: filters
          });

          this.applyFilters();
          this.closeSimpleDropdown();
        }
      }
    } else if (ctx.tab === 1) {
      const filters = this.data.roomFilters;
      const filter = filters[ctx.filterIndex];

      if (isReset) {
        filters[ctx.filterIndex].selectedValue = undefined;
        filters[ctx.filterIndex].active = false;
        const originalTexts = ["类型", "性别", "地点", "日期"];
        filters[ctx.filterIndex].text = originalTexts[ctx.filterIndex];

        this.setData({
          roomFilters: filters
        });

        this.applyFilters();
        this.closeSimpleDropdown();
      } else {
        const option = filter.options.find((opt) => {
          return (
            opt.value === optionId || String(opt.value) === String(optionId)
          );
        });

        if (option) {
          filters[ctx.filterIndex].selectedValue = option.value;
          filters[ctx.filterIndex].active = true;
          filters[ctx.filterIndex].text = option.text;

          this.setData({
            roomFilters: filters
          });

          this.applyFilters();
          this.closeSimpleDropdown();
        }
      }
    } else if (ctx.tab === 2) {
      const filters = this.data.ticketFilters;
      const filter = filters[ctx.filterIndex];

      if (isReset) {
        filters[ctx.filterIndex].selectedValue = undefined;
        filters[ctx.filterIndex].active = false;
        const originalTexts = ["类型", "整/残", "雪场", "日期"];
        filters[ctx.filterIndex].text = originalTexts[ctx.filterIndex];

        this.setData({
          ticketFilters: filters
        });

        this.applyFilters();
        this.closeSimpleDropdown();
      } else {
        const option = filter.options.find((opt) => {
          return (
            opt.value === optionId || String(opt.value) === String(optionId)
          );
        });

        if (option) {
          filters[ctx.filterIndex].selectedValue = option.value;
          filters[ctx.filterIndex].active = true;
          filters[ctx.filterIndex].text = option.text;

          this.setData({
            ticketFilters: filters
          });

          this.applyFilters();
          this.closeSimpleDropdown();
        }
      }
    }
  },

  /**
   * 关闭SimpleDropdown组件
   */
  closeSimpleDropdown: function () {
    this.setData({
      simpleDropdownOpen: false
    });
  },

  /**
   * 刷新SimpleDropdown panel位置
   */
  updateSimpleDropdownPanelPosition: function () {
    if (!this.data.simpleDropdownOpen) return;
    const that = this;
    wx.createSelectorQuery()
      .select(".filter-section")
      .boundingClientRect()
      .exec(function (res) {
        const rect = res && res[0];
        if (!that.data.simpleDropdownOpen || !rect) return;
        const topVal = rect.top + rect.height;
        that.setData({
          simpleDropdownTop: topVal
        });
      });
  },

  /**
   * 打开雪场筛选弹窗
   */
  openSkiFilterPopup: function (context) {
    if (
      this.data.skiDropdownOpen &&
      this.data.skiFilterContext &&
      this.data.skiFilterContext.tab === context.tab &&
      this.data.skiFilterContext.filterIndex === context.filterIndex
    ) {
      this.closeSkiDropdown();
      return;
    }

    let selectedSkiId = null;
    if (context.tab === 0) {
      const carpoolFilters = this.data.carpoolFilters || [];
      const skiFilter = carpoolFilters[context.filterIndex];
      if (
        skiFilter &&
        skiFilter.selectedValue !== undefined &&
        skiFilter.selectedValue !== null
      ) {
        selectedSkiId = skiFilter.selectedValue;
      }
    } else if (context.tab === 1) {
      const roomFilters = this.data.roomFilters || [];
      const skiFilter = roomFilters[context.filterIndex];
      if (
        skiFilter &&
        skiFilter.selectedValue !== undefined &&
        skiFilter.selectedValue !== null
      ) {
        selectedSkiId = skiFilter.selectedValue;
      }
    } else if (context.tab === 2) {
      const ticketFilters = this.data.ticketFilters || [];
      const skiFilter = ticketFilters[context.filterIndex];
      if (
        skiFilter &&
        skiFilter.selectedValue !== undefined &&
        skiFilter.selectedValue !== null
      ) {
        selectedSkiId = skiFilter.selectedValue;
      }
    }

    const that = this;
    wx.createSelectorQuery()
      .select(".filter-section")
      .boundingClientRect()
      .exec(function (res) {
        const rect = res && res[0];
        const top = rect ? rect.top + rect.height : 100;
        that.setData({
          skiDropdownOpen: true,
          skiDropdownTop: top,
          skiFilterContext: context,
          selectedSkiId: selectedSkiId
        });
      });
  },

  /**
   * SkiDropdown组件change事件处理
   */
  onSkiDropdownChange: function (e) {
    const optionId = e.detail.value;
    const optionName = e.detail.name;
    const ctx = this.data.skiFilterContext;

    if (!ctx) {
      this.closeSkiDropdown();
      return;
    }

    const isReset =
      optionId === null || optionId === undefined || optionId === "";

    if (ctx.tab === 0) {
      const filters = this.data.carpoolFilters;
      filters[ctx.filterIndex].selectedValue = isReset ? undefined : optionId;
      filters[ctx.filterIndex].active = !isReset;
      filters[ctx.filterIndex].text = isReset ? "雪场" : optionName;
      this.setData({
        carpoolFilters: filters,
        selectedSkiId: isReset ? null : optionId
      });
      this.applyFilters();
    } else if (ctx.tab === 1) {
      const filters = this.data.roomFilters;
      filters[ctx.filterIndex].selectedValue = isReset ? undefined : optionId;
      filters[ctx.filterIndex].active = !isReset;
      filters[ctx.filterIndex].text = isReset ? "地点" : optionName;
      this.setData({
        roomFilters: filters,
        selectedSkiId: isReset ? null : optionId
      });
      this.applyFilters();
    } else if (ctx.tab === 2) {
      const filters = this.data.ticketFilters;
      filters[ctx.filterIndex].selectedValue = isReset ? undefined : optionId;
      filters[ctx.filterIndex].active = !isReset;
      // 根据filterIndex判断是雪场还是其他筛选器
      if (ctx.filterIndex === 2) {
        filters[ctx.filterIndex].text = isReset ? "雪场" : optionName;
      } else {
        filters[ctx.filterIndex].text = isReset ? "地点" : optionName;
      }
      this.setData({
        ticketFilters: filters,
        selectedSkiId: isReset ? null : optionId
      });
      this.applyFilters();
    }
  },

  /**
   * 关闭SkiDropdown组件
   */
  closeSkiDropdown: function () {
    this.setData({ skiDropdownOpen: false });
  },

  /**
   * 关闭DatePicker组件
   */
  closeDatePicker: function () {
    this.setData({ datePickerOpen: false });
  },

  /**
   * DatePicker 事件：重置
   */
  onDateReset: function () {
    const activeTab = this.data.activeTab;
    if (activeTab === 0) {
      const filters = this.data.carpoolFilters;
      filters[3].text = "日期";
      filters[3].active = false;
      filters[3].selectedValue = undefined;
      this.setData({ carpoolFilters: filters });
    } else if (activeTab === 1) {
      const filters = this.data.roomFilters;
      filters[3].text = "日期";
      filters[3].active = false;
      filters[3].selectedValue = undefined;
      this.setData({ roomFilters: filters });
    } else if (activeTab === 2) {
      const filters = this.data.ticketFilters;
      filters[3].text = "日期";
      filters[3].active = false;
      filters[3].selectedValue = undefined;
      this.setData({ ticketFilters: filters });
    }
    this.applyFilters();
  },

  /**
   * DatePicker 事件：确认
   */
  onDateConfirm: function (e) {
    const selectedDate = e.detail && e.detail.value;
    const activeTab = this.data.activeTab;
    const label = this.formatDateLabel(selectedDate);

    if (activeTab === 0) {
      const filters = this.data.carpoolFilters;
      filters[3].text = label || "日期";
      filters[3].active = !!selectedDate;
      filters[3].selectedValue = selectedDate;
      this.setData({ carpoolFilters: filters });
    } else if (activeTab === 1) {
      const filters = this.data.roomFilters;
      filters[3].text = label || "日期";
      filters[3].active = !!selectedDate;
      filters[3].selectedValue = selectedDate;
      this.setData({ roomFilters: filters });
    } else if (activeTab === 2) {
      const filters = this.data.ticketFilters;
      filters[3].text = label || "日期";
      filters[3].active = !!selectedDate;
      filters[3].selectedValue = selectedDate;
      this.setData({ ticketFilters: filters });
    }

    this.applyFilters();
    this.closeDatePicker();
  },

  /**
   * DatePicker 事件：选择日期
   */
  onDateSelect: function (e) {
    // 单个日期选择，无需即时刷新列表
  },

  /**
   * DatePicker 事件：上一月
   */
  prevMonth: function () {},

  /**
   * DatePicker 事件：下一月
   */
  nextMonth: function () {},

  /**
   * 格式化日期标签
   */
  formatDateLabel: function (date) {
    if (!date) return "";
    return this.formatForPickerTag(date);
  },

  formatForPickerTag: function (dateStr) {
    try {
      const d = new Date(dateStr);
      const m = String(d.getMonth() + 1);
      const day = String(d.getDate());
      return m + "." + day;
    } catch (_) {
      return dateStr;
    }
  },

  /**
   * 页面滚动事件 - 滚动时关闭所有下拉框
   */
  onPageScroll: function () {
    if (this.data.skiDropdownOpen) {
      this.closeSkiDropdown();
    }
    if (this.data.simpleDropdownOpen) {
      this.closeSimpleDropdown();
    }
    if (this.data.datePickerOpen) {
      this.closeDatePicker();
    }
  },

  /**
   * 刷新雪场弹窗panel位置
   */
  updateSkiDropdownPanelPosition: function () {
    if (!this.data.skiDropdownOpen) return;
    const that = this;
    wx.createSelectorQuery()
      .select(".filter-section")
      .boundingClientRect(function (rect) {
        if (!that.data.skiDropdownOpen || !rect) return;
        const topVal = rect.top + rect.height;
        that.setData({
          skiDropdownTop: topVal
        });
      })
      .exec();
  },

  /**
   * 返回按钮
   */
  onBackClick: function () {
    wx.navigateBack();
  },

  /**
   * 测试接口联调
   */
  testApiIntegration: function () {
    console.log("开始测试拼车接口联调...");

    // 测试参数构建
    const testParams = this.buildCarpoolRequestParams();
    console.log("构建的请求参数:", testParams);

    // 测试数据转换
    const mockApiData = [];

    const transformedData = this.transformCarpoolData(mockApiData);
    console.log("转换后的数据:", transformedData);

    wx.showToast({
      title: "接口联调测试完成",
      icon: "success"
    });
  },

  /**
   * 测试拼房接口联调
   */
  testRoomApiIntegration: function () {
    console.log("开始测试拼房接口联调...");

    // 测试参数构建
    const testParams = this.buildRoomRequestParams();
    console.log("构建的拼房请求参数:", testParams);

    // 测试数据转换
    const mockRoomApiData = [];

    const transformedRoomData = this.transformRoomData(mockRoomApiData);
    console.log("转换后的拼房数据:", transformedRoomData);
  },

  /**
   * 测试雪票接口联调
   */
  testTicketApiIntegration: function () {
    console.log("开始测试雪票接口联调...");

    // 测试参数构建
    const testParams = this.buildTicketRequestParams();
    console.log("构建的雪票请求参数:", testParams);

    // 测试数据转换
    const mockTicketApiData = [];

    const transformedTicketData = this.transformTicketData(mockTicketApiData);
    console.log("转换后的雪票数据:", transformedTicketData);

    wx.showToast({
      title: "雪票接口联调测试完成",
      icon: "success"
    });
  }
});
